package com.eye.system.service.impl;

import com.eye.system.domain.Location;
import com.eye.system.exception.DMPException;
import com.eye.system.mapper.LocationMapper;
import com.eye.system.search.LocationSearch;
import com.eye.system.service.LocationService;
import com.eye.system.util.PageRequest;
import com.eye.system.util.PageResult;
import com.eye.system.util.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("locationService")
public class LocationServiceImpl implements LocationService {

    @Resource
    private LocationMapper locationMapper;

    @Override
    public Integer addLocation(Location location) {
        if (location != null) {
            int add = locationMapper.insert(location);
            if (add > 0) {
                return add;
            }
            throw new DMPException("添加地点失败");
        }
        throw new DMPException("无效参数");
    }

    @Override
    public Integer deleteLocation(Integer id) {
        int delete = locationMapper.deleteById(id);
        if (delete > 0) {
            return delete;
        }
        throw new DMPException("删除地点失败");
    }

    @Override
    public Integer updateLocation(Integer id, Location location) {
        Location l = locationMapper.selectById(id);
        if (l == null) {
            throw new DMPException("该地点不存在");
        }
        Integer update = locationMapper.updateByIdSelective(location);
        if (update > 0) {
            return update;
        }
        throw new DMPException("修改地点失败");
    }

    @Override
    public Location selectById(Integer id) {
        Location location = locationMapper.selectById(id);
        if (location != null) {
            return location;
        }
        throw new DMPException("地点删除失败");
    }

    @Override
    public PageResult selectPaging(LocationSearch locationSearch) {
        PageRequest pageRequest = new PageRequest();
        return PageUtils.getPageResult(pageRequest, getPageInfo(locationSearch));
    }

    private PageInfo<Location> getPageInfo(LocationSearch locationSearch) {
        PageHelper.startPage(locationSearch.getPageNum(), locationSearch.getPageSize());
        List<Location> locationList = locationMapper.select(locationSearch);
        return new PageInfo<Location>(locationList);
    }
}
